$m(function(args) {
	var flowInfo = args.data;
	var callback = args.callback;
	var initDialog = function() {
		var taskhtml = $('.tempo-mine-flow-task-dialog').html();
		var taskDialog = $("<div>").append($(taskhtml));
		taskDialog.dialog({
			width : 750,
			height: 550,
			title: TempoUtils.locale('mine.create_new_task'),
			modal:true,
			resizable: false,
			close:function(){
				taskDialog.dialog("destroy").remove();
			},
			open:function(){
				taskDialog.find("input[name='name']").text("");
				initFormData(taskDialog);
				setFlowParams(taskDialog, flowInfo);
				// 调度服务不可用的情况下，禁用保存按钮
				$.post(contextPath + '/api/ai/app/schedule/group', function(response) {
					if(!response.success) {
						$('#add-schedule-dialog-confirm-btn').button('disable');
						$("<div/>").alert({msg : TempoUtils.locale("mine.schedule_service_unavilable"), height : 180});
					}
				});
			},
			buttons:[{
				text: TempoUtils.locale('mine.publish-dialog-sure'),
				id: 'add-schedule-dialog-confirm-btn',
				click:function(){
					if(validate(taskDialog)){
						saveTaskConfig(taskDialog, flowInfo);
					}else {
						return false;
					}
				}
			},{
				text:TempoUtils.locale('mine.publish-dialog-cancel'),
				click:function(){
					taskDialog.dialog("close");
				}
			}]
		});
	};
	var alert = function(text) {
		$("<div/>").alert({
			msg : text,
			title : TempoUtils.locale("mine.prompt")
		});
	}
	/**
	 * 增加新建调度时，清除具体时间仍可以新建调度校验
	 */
	var validate = function (taskDialog) {
		var triggertype = taskDialog.find(".new-triggertype").val();
		if(triggertype=="0"){
			var jutiTime = taskDialog.find(".new-shechduing-juti-time").val();
			if(jutiTime==""){
				alert("请选择具体时间！");
				return false;
			}
		}else if(triggertype=="1"){
			//调度周期为“周”
			var jutiTime = taskDialog.find(".new-shechduing-juti-time").val();
			if(jutiTime==""){
				alert("请选择具体时间！");
				return false;
			}
		}else if(triggertype=="2"){
			//调度周期为月
			var jutiTime = taskDialog.find(".new-shechduing-juti-time").val();
			if(jutiTime==""){
				alert("请选择具体时间！");
				return false;
			}
		}

		return true;
	}
	var initFormData = function(dialog) {
		TempoUtils.parserUi(dialog, {});
		dialog.find('.datefield').datepicker({
			dateFormat: 'yy-mm-dd',
			onClose : function(){
				if($(this).val()){
					$(this).validatebox('response', $(this).val());
				}
			},
			onSelect :function(){
				
			},
			onChangeMonthYear : function(year, month, inst){
				var month = inst.selectedMonth + 1;
				var day = inst.selectedDay;
				var format = function(v) { return String(v).length > 1 ? v : ('0' + v) }
				$(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
				$.datepicker._hideDatepicker(this);
			}
		});
		dialog.find('.timefield').timepicker({
			onClose : function(){
				if($(this).val()){
					$(this).validatebox('response', $(this).val());
				}
			},
			onSelect :function(){
				
			},
			timeInput : true
		});
		
		var internalInput = dialog.find('input[name=interval]');
		//调度周期
		dialog.find('select[name="triggertype"]').selectmenu({
			selectFirst: false,
			change: function(e, ui) {
				console.log(e, ui);
				changeTriggerType(ui.item.value);
			}
		});
		//任务提交报错重试
		dialog.find('select[name="retry"]').selectmenu({
			selectFirst: true,
			change: function(e, ui) {
				changeTriggerRunErrorType(ui.item.value);
			}
		});
		//重试次数
		var changeTriggerRunErrorType = function (value) {
			if(value=="0"){
				dialog.find("td[name=retryNum]").hide();
			}else{
				dialog.find("td[name=retryNum]").show();
			}
		}

		//切换调度周期
		var changeTriggerType = function(value) {
			if(value == "-2") {
				//分钟
				switchShowItem(dialog, false, true, false, true, 1);
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-minute"));
				internalInput.numberbox({max: 59, min: 1}).val(30);
			} else if(value == "-1") {
				//小时
				switchShowItem(dialog, false, true, false, true, 1);
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-hour"));
				internalInput.numberbox({max: 23, min: 1}).val(3);
			} else if(value == "0") {
				//天
				switchShowItem(dialog, false, false, true, true, 3);
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-day"));
				internalInput.numberbox({max: 31, min: 1}).val(1);
			} else if(value == "1") {
				//周
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-week"));
				switchShowItem(dialog, true, false, true, false);
				buildWeeks(dialog);
				internalInput.numberbox({max: 6, min: 1}).val(1);
			} else if(value == "2") {
				//月
				switchShowItem(dialog, true, false, true, true, 2);
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-month"));
				buildDays(dialog);
				internalInput.numberbox({max: 11, min: 1}).val(1);
			}
		}
		
		dialog.find('select[name="triggertype"]').val(0).selectmenu('refresh');
		dialog.find('select[name="retry"]').val(0).selectmenu('refresh');
		changeTriggerType(0);
		changeTriggerRunErrorType(0);
		dialog.find('input[name=starttime]').val(DateUtils.formatDate(new Date()));
	}
	
	var setFlowParams = function(dialog, flowInfo) {
		var flowid = flowInfo.id;
		dialog.find('#flowParamsContainer').hide();
		var paramLabel = TempoUtils.locale("mine.publish-mine-job-param-label");
		dialog.find("#publish-mine-job-param-label").text(flowInfo.name+'-'+paramLabel);
		var grid = dialog.find('#setFlowParamTable').find('tbody').empty();
		$.ajax({
			url : contextPath+"/api/ai/app/schedule/flowparams/get/" + flowid,
			type : 'post',
			success : function(result){
				if(result && result.data && result.data.length > 0){
					initParamGrid(dialog, result.data);
				}
			}
		});
	}
	
	var saveTaskConfig = function(dialog, flowInfo) {
		if(!validateForm(dialog, flowInfo)){
			return;
		}
		var job = {
				trigger : {
				},
				publishFlowIds : []
		};
		var triggerParam = {};
		var trigger = job.trigger;
		//调度信息
		var jobconfig = dialog.find('#tempo-mine-flow-config-task').serializeArray();
		
		// 添加对复选框值的处理，转变为一个属性值
		$.each(jobconfig, function(index, item){
			if(!item.name.startsWith('flow_')){
				if(trigger[item.name]) {
					if(Array.isArray(trigger[item.name])) {
						trigger[item.name].push(item.value);
					} else {
						trigger[item.name] = [trigger[item.name], item.value];
					}
				} else {
					trigger[item.name] = item.value;
				}
			}
		});
		
		if((dialog.find('input[name=dayofweek]').length && !trigger['dayofweek']) 
				|| (dialog.find('input[name=dayofmonth]').length && !trigger['dayofmonth'])) {
			$("<div/>").alert({msg : TempoUtils.locale("mine.qingxuanzeyunxingshijian"), height : 180});
			return false;
		}
		// 处理数组类型值，转换为逗号分割的字符串
		Array.isArray(trigger['dayofweek']) && (trigger['rundate'] = trigger['dayofweek'].join(','));
		Array.isArray(trigger['dayofmonth']) && (trigger['rundate'] = trigger['dayofmonth'].join(','));
		trigger['dayofweek']  && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofweek']);
		trigger['dayofmonth'] && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofmonth']);
		delete trigger['dayofweek'];
		delete trigger['dayofmonth'];
		console.log(JSON.stringify(trigger))
		trigger.interval = Number(trigger.interval);
		if(trigger.retryNum) trigger.retryNum = Number(trigger.retryNum);
		var relatedFlow = [];
		var rflowObj = {};
		rflowObj["flow_current"] = flowInfo.id;
		relatedFlow.push(rflowObj);
		triggerParam.flowsInJob = relatedFlow;
		job.publishFlowIds = flowInfo.id;
		job.publishFlowNames = flowInfo.name;;
		//流程配置参数
		triggerParam.flowsParam = {};
		triggerParam.flowsParam[flowInfo.id] = getCurrentFlowParams(dialog);
		job.trigger.param = JSON.stringify(triggerParam);
		var process = $("<div/>").tempoprogressbar();
		var url = contextPath + '/api/ai/app/schedule/job/save';
		$.ajax({
			url : url,
			type : 'post',
			data : JSON.stringify(job),
			contentType : 'application/json',
			success : function(obj) {
				process.tempoprogressbar("destroy");
				if (obj &&  obj.data && obj.data.status) {
					dialog.dialog("destroy");
					callback(obj.data, obj.data.job);
				} else {
					$("<div/>").alert({msg : obj.data.error, height : 180, width: 400});
				}
			},
			error:function(data){
				process.tempoprogressbar("destroy");
			}
		});
	}
	
	/**
	 * 调度时间切换方法
	 */
	var switchShowItem = function(dialog, timesRow, timeRange, dayTime, interval, dayMonthYear) {
		dialog.find('.day-of-time-range-row input[name=stime]').change();
		dialog.find('.day-of-time-row input[name=stime]').change();
		dialog.find('.day-of-time-range-row input[name=stime]').val("00:00")
		dialog.find('.day-of-time-row input[name=stime]').val("00:00")
		var _onoff = $.fn.onoff;
		$.fn.onoff = function(value) {
			var element = $(this);
			if(value) {
				element.show();
			} else {
				element.hide();
			}
			element.find('input').each(function(index, ele) {
				var role = $(ele).attr('ui-role');
				if(role == 'validatebox' || role == 'numberbox') {
					!value ? $(ele)[role]('disable') : $(ele)[role]('enable');
				}
			});
		}
		dialog.find('.times-row').onoff(timesRow);
		dialog.find('.times-board').empty();
		if(timeRange) {
			dialog.find('.day-of-time-range-row input[name=stime]')
				.validatebox({required: true}).validatebox('validate');
		} else {
			dialog.find('.day-of-time-row input[name=stime]')
				.validatebox({required: true}).validatebox('validate');
		}
		dialog.find('.day-of-time-range-row').onoff(timeRange);
		dialog.find('.day-of-time-row').onoff(dayTime);
		dialog.find('.time-interval-row').onoff(interval);
		if(interval && dayMonthYear != undefined) {
			dialog.find('.time-of-day').onoff(dayMonthYear == 1);
			dialog.find('input.time-of-day').hide().radio('check', dayMonthYear == 1 ? 'outer-day' : '');
			dialog.find('.day-of-month').onoff(dayMonthYear == 2);
			dialog.find('input.day-of-month').hide().radio('check', dayMonthYear == 2 ? 'outer-month' : '');
			dialog.find('.month-of-year').onoff(dayMonthYear == 3);
			dialog.find('input.month-of-year').hide().radio('check', dayMonthYear == 3 ? 'outer-year' : '');
		}
		$.fn.onoff = _onoff;
	}
	/**
	 * 构建周页面
	 */
	var buildWeeks = function(dialog) {
		var board = dialog.find('.times-board');
		var weeks = [2, 3, 4, 5, 6, 7, 1];
		var weekName = [TempoUtils.locale("mine.xinqiyi"),
		                TempoUtils.locale("mine.xinqier"), 
		                TempoUtils.locale("mine.xinqisan"),
		                TempoUtils.locale("mine.xinqisi"),
		                TempoUtils.locale("mine.xinqiwu"),
		                TempoUtils.locale("mine.xinqiliu"),
		                TempoUtils.locale("mine.xinqitian")
		                ];
		weeks.forEach(function(e, i) {
			var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
			$("<input ui-role='checkbox' name='dayofweek' type='checkbox'/>").val(e).appendTo(span);
			$("<label/>").text(weekName[i]).appendTo(span);
		});
		TempoUtils.parserUi(board, {});
	};
	
	/**
	 * 构建天页面
	 */
	var buildDays = function(dialog) {
		var board = dialog.find('.times-board');
		for(var i = 1; i <= 31; i++) {
			var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
			$("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
				.val(i)
				.addClass('day-of-month-' + i)
				.appendTo(span);
			$("<label/>").text(i + TempoUtils.locale("mine.hao")).appendTo(span);
		}
		var lastSpan = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
		$("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
			.val("L")
			.addClass('day-of-month-L')
			.appendTo(lastSpan);
		$("<label/>").text(TempoUtils.locale("mine.zuihouyitian")).appendTo(lastSpan);
		TempoUtils.parserUi(board, {});
	}
	var initParamGrid = function(dialog, ps){
		var grid = dialog.find('#setFlowParamTable');
		dialog.find('#flowParamsContainer').show();
		if (ps && ps.length > 0) {
			for (var i = 0; i < ps.length; i++) {
				// 屏蔽系统参数
				if ('system.appId' == ps[i].paramName) {
					continue;
				}
				var tr = $('<tr>').appendTo(grid);
				var p = ps[i];
				var paramName = p.paramName;
				var paramValue = p.paramValue;
				var paramType = p.paramType;
				var paramId = p.paramId;
				var nodeType = p.nodeType;
				// 在新建调度的弹框里添加参数说明，兼容一下，以前没有置为空
				var paramDesc = "";
				if (p.paramDesc) {
					paramDesc = p.paramDesc;
				}
				var paramNameTd = $('<td>').appendTo(tr);
				var paramNameInput = $('<input name="paramName">').addClass('flow_paramname').appendTo(paramNameTd).val(paramName);
				$('<input name="paramType" type="hidden">').addClass('flow_paramtype').appendTo(paramNameTd).val(paramType);
				$('<input name="paramId" type="hidden">').addClass('flow_paramid').appendTo(paramNameTd).val(paramId);
				var paramValueTd = $('<td>').appendTo(tr);
				var paramValueInput = $('<select name="paramValue">').addClass('flow_paramvalue').appendTo(paramValueTd);
				paramNameInput.validatebox({width : 100, readonly : true, disabled: 'disabled'});
				if (nodeType) {
					$('<input name="nodeType" type="hidden">').addClass('flow_nodetype').appendTo(paramNameTd).val(nodeType);
				}
				// 向表格中添加参数说明数据
				var paramDescTd = $('<td>').appendTo(tr);
				var paramDescInput = $('<input name="paramDesc">').addClass('flow_paramdesc').appendTo(paramDescTd).val(paramDesc);
				paramDescInput.validatebox({width : 100, readonly : true, disabled: 'disabled'});
				paramNameInput.attr('title', paramName);
				getFlowParams(paramType, paramValueInput, paramValue,nodeType);
				// 参数说明 值回显
				paramDescInput.attr('title', paramDesc);
			}
		}
		// 判断流程参数里是否有值，没有值侧不显示，添加这个是因为有些节点有一个默认流程参数为system.appId
		if (grid.find('tbody tr').length == 0) {
			dialog.find('#flowParamsContainer').hide();
		}
	};
	var getFlowParams = function(type, paramValueInput, value, nodeType) {
		var pss = [];
		if(type == 'datasource'){
			var process = $("<div/>").tempoprogressbar();
			$.ajax({
				url:contextPath + '/api/ai/node/io/list-datasources',
			    type:'post',
			    success:function(rs) {
			    	process.tempoprogressbar("destroy");
			    	var data = rs.data || [];
					var itemHtml = [];
					for(var i =0;i<data.length;i++){
						var dataItem = data[i];
						// 屏蔽模型数据源、presto数据源、impala数据源
						if (nodeType == 'readrdbms') {
							if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1) {
								continue;
							}
						}
						if (nodeType == 'writerdbms') {
							if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1 || (dataItem.purpose && dataItem.purpose != "1")) {
								continue;
							}
						}

						if (nodeType == 'readhive') {
							if (dataItem.type != 'hive') {
								continue;
							}
						}
						if(nodeType == 'writehive'){
							if('hive' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")){
								continue;
							}
						}
						if (nodeType == "readinfluxdb") {
							if (!(dataItem.type == "influxdb" || dataItem.type == "influxdb2")) {
								continue;
							}
						}
						if( nodeType == "readiotdb"){
							if (dataItem.type != 'iotdb') {
								continue;
							}
						}
						if( nodeType == "writeiotdb"){
							//不是iotdb  或者不能写入
							if ('iotdb' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")) {
								continue;
							}
						}
						itemHtml.push('<option value="' + dataItem.code + '">' + dataItem.name + '</option>')
					}
					var html = itemHtml.join('');
					paramValueInput.html(html);
					paramValueInput.selectmenu({
						editable : false,
						width : 150,
						labelForTitle: true
					}).selectmenu('setValue', value).selectmenu('refresh');
			    }
			});
		} else {
			var items = TempoMineUtils.getConstFlowParams();
			if(items){
				for(name in items){
					pss.push('<option value="' + name + '">' + items[name] + '</option>')
				}
			}
			var html = pss.join('');
			paramValueInput.html(html);
			paramValueInput.selectmenu({
				editable : true,
				width : 150,
				labelForTitle: true
			}).selectmenu('setValue', value);
		}
		
	}

	//校验
	var validateForm = function(dialog, isEdit) {
		var v = dialog.find('form').formValidate();
		var jobconfig = TempoUtils.getRecord(dialog.find('form'));
		var triggerName = jobconfig.name;
		var isRaname = false;
		$.ajax({
			url : contextPath + '/api/ai/mine/publish/listAllTriggerName',
			type : 'post',
			async:false,
			success : function(triggerNames) {
				if (triggerNames) {
					isRaname = triggerNames.indexOf(triggerName) > -1;
				}
			}
		});
		if (isRaname) {
			$("<div/>").alert({msg : TempoUtils.locale("mine.triggernameerror"), height : 180});
			return false;
		}
		return v && (function(){
			console.log(jobconfig);
			if(jobconfig.starttime && jobconfig.endtime) {
				var s = new Date(jobconfig.starttime);
				var e = new Date(jobconfig.endtime);
				if(s.getTime() > e.getTime()) {
					$("<div/>").alert({msg : TempoUtils.locale("mine.shengxiaoshijianerror"), height : 180});
					return false;
				}
			}
			if(jobconfig.stime && jobconfig.etime) {
				if(jobconfig.stime >= jobconfig.etime && jobconfig.runType == 'inner-day') {
					$("<div/>").alert({msg : TempoUtils.locale("mine.kaishishijianerror"), height : 180});
					return false;
				}
				if(jobconfig.stime == jobconfig.etime && jobconfig.runType == 'outer-day') {
					$("<div/>").alert({msg : TempoUtils.locale("mine.schedule-stime-not-equls-etime"), height : 180});
					return false;
				}
			}
			return true;
		})();
	}
	var getCurrentFlowParams = function(dialog){
		var paramsTable = dialog.find('#flowParamsContainer table');
		var currentFlowParams = []
		var paramsLine = paramsTable.find('tbody tr');
		paramsLine.each(function(i){
			var paramName = $(this).find('input.flow_paramname').val();
			var paramType = $(this).find('input.flow_paramtype').val();
			var paramId = $(this).find('input.flow_paramid').val();
			var paramValue = $(this).find('select.flow_paramvalue').selectmenu('getValue');
			var param = {};
			// 获取参数说明
			if ($(this).find('input.flow_nodetype').length > 0) {
				var nodeType = $(this).find('input.flow_nodetype').val();
				param.nodeType = nodeType;
			}
			var paramDesc = $(this).find('input.flow_paramdesc').val();
			param.paramName = paramName;
			param.paramValue = paramValue;
			param.paramId = paramId;
			param.paramType = paramType;
			// 添加参数说明
			param.paramDesc = paramDesc;
			if(!$.isEmptyObject(param)){
				currentFlowParams.push(param);
			}
		});
		return currentFlowParams;
	}
	
	initDialog();
});
